<template>
  <div :id="id" class="xterm"/>
</template>

<script setup>
import {defineExpose, onMounted, ref} from 'vue'
import {v4} from 'uuid'
import "xterm/css/xterm.css"
import {Terminal} from 'xterm'
import {FitAddon} from 'xterm-addon-fit'

import EventBus from "@/util/EventBus";
import socket from "@/util/SocketUtil";

const options = defineProps(['username', 'ip', 'password'])
const id = ref("xterm" + v4())

let term;
onMounted(() => {
  term = new Terminal({
    rendererType: 'canvas',
    // cursorBlink: true, // 光标闪烁
    cursorStyle: "bar", // 光标样式 null | 'block' | 'underline' | 'bar'
    // scrollback: 800, // 回滚
    // tabStopWidth: 8, // 制表宽度
    // screenKeys: true,


    allowProposedApi: true,
    fontSize: 14,
    cursorBlink: true,
    disableStdin: false,
    LogLevel: 'debug'

  });
  term.onData(data => sendClientData(data))
  const xterm = document.getElementById(id.value)
  term.open(xterm)

  const fitAddon = new FitAddon()
  term.loadAddon(fitAddon)
  fitAddon.fit()
  term.focus()
// 在页面上显示连接中...
  write(getGreenStr(`正在连接服务器:${options.ip}...\r\n`));
  connect()
  EventBus.on(id.value, msg => {
    write(msg)
  })
})

function connect() {
  send({
    operate: 'connect',
    host: options.ip,
    port: '22',
    username: options.username,
    password: options.password
  })
}

function disconnect() {
  send({
    operate: 'disconnect'
  })
}

function getGreenStr(str) {
  return '\x1B[32m' + str + '\x1B[0m'
}

function sendClientData(data) {
  //发送指令
  switch (socket.value.readyState) {
    case WebSocket.CONNECTING:
      console.error("正在连接中")
      break
    case WebSocket.OPEN:
      send({"operate": "command", "command": data})
      break
    case WebSocket.CLOSING:
      console.error("正在关闭中")
      break
    case WebSocket.CLOSED:
      console.error("已关闭")
      break
    default:
      break
  }
}

function send(msg) {
  msg.id = id.value
  socket.value.send(JSON.stringify(msg))
}

function write(str) {
  term.write(str)
}

function _generateEndpoint() {
  let protocol
  if (window.location.protocol === 'https:') {
    protocol = 'wss://';
  } else {
    protocol = 'ws://';
  }
  return protocol + '127.0.0.1:8080/webssh';
}

defineExpose({
  disconnect
})

</script>


<style scoped>
.xterm {
  background-color: #020202;
}
</style>